package com.nowcoder.community.controller.advice;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiexu
 * @create 2022-06-06 09:42
 */
@ControllerAdvice(annotations = Controller.class) // 只扫描带有@Controller注解的bean
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class}) // 表示处理所有异常
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        logger.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        // 判断是普通请求还是异步请求
        String xRequestedWith = request.getHeader("x-requested-with");
        // 说明是一个异步请求，发生异常需要返回json格式的字符串
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/plain;charset=UTF-8");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(CommunityUtil.getJSONString(1, "服务器异常！"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else { // 普通请求的异常就直接返回错误页面
            try {
                response.sendRedirect(request.getContextPath() + "/error");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
